﻿namespace Groundwork.Core.Threading
{
	using System;
	using System.Threading;
	
	/// <summary>
    /// Aquires a system wide mutex allowing us to control access to card reader methods
    /// </summary>
    public class AquireMutext : IDisposable
    {
        private static Mutex mutextLock = new Mutex(false);
        private string methodName = string.Empty;

        /// <summary>
        /// Aquire a lock, Default Expiry of applied mutext is 30 Seconds. If you expect the lock to persist for longer please
        /// override the expiry using the overload.
        /// </summary>
        /// <param name="method"></param>
        public AquireMutext(string method)
        {
        	TimeSpan expiry = TimeSpan.FromSeconds(30);
            methodName = method;
            if (!string.IsNullOrEmpty(methodName))
            {
            	Console.WriteLine("Lock Aquired on {0}", method);
            }

            mutextLock.WaitOne(expiry);
        }
        
        /// <summary>
        /// Aquire a lock
        /// </summary>
        /// <param name="method"></param>
        public AquireMutext(string method, TimeSpan expiry)
        {
            methodName = method;
            if (!string.IsNullOrEmpty(methodName))
            {
            	Console.WriteLine("Lock Aquired on {0}", methodName);
            }

            mutextLock.WaitOne(expiry);
        }
        		
		public void Release()
		{
			Console.WriteLine("Lock Released manually on {0}", methodName);
			mutextLock.ReleaseMutex();
		}
		
        /// <summary>
        /// Release the Lock
        /// </summary>
        public void Dispose()
        {
            if (!string.IsNullOrEmpty(methodName))
            {
            	Console.WriteLine("Lock Released on {0}", methodName);
            }

            mutextLock.ReleaseMutex();
        }
    }
}
